package com.li.shop.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.li.shop.domain.News;
import com.li.shop.domain.NewsExample;
import com.li.shop.mapper.NewsMapper;
import com.li.shop.service.NewsService;
import com.li.shop.utils.SearchNewsRequest;
import com.li.shop.utils.SearchNewsResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsMapper newsMapper;

    @Override
    public List<News> listNews() {
        return newsMapper.listNews();
    }

//王志文
    @Override
    //public List<News> listNews(Integer pageSize,Integer pageNum) {
    public SearchNewsResponse listNews(Integer pageSize, Integer pageNum, String keyword) {
        //PageHelper.startPage(1,10);
        PageHelper.startPage(pageNum,pageSize);
        NewsExample example =new NewsExample();
        if (StringUtils.isNotBlank(keyword)) {
            example.createCriteria().andNewscontentLike("%"+keyword+"%");
        }
        List<News> newss= newsMapper.selectByExample(example);
        return  new SearchNewsResponse(((Page)newss).getTotal(),newss);
        //return NewsMapper.selectByExample(new NewsExample());//分页后返回的page对象，page中有一个list对象
    }


    @Override
    public int deleteNewsByPrimaryKey(String id) {
        return newsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public News findNewsByPrimaryKey(String id) {
        return newsMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<News> searchNewss(SearchNewsRequest request) {
        NewsExample ex = new NewsExample();
//        ex.createCriteria().andNewsIdEqualTo(request.getId());
//        ex.or().andLastNameLike("%" + request.getName() + "%");
        return newsMapper.selectByExample(ex);
    }

    @Override
    public int saveNews( News news) {
        System.out.println(news.getNewsid()+"newsid");
        if(StringUtils.isNotBlank( news.getNewsid()) ){
            //if( news.getuId()!=null ){
            //把domain类中的uId类型转化为String
            return newsMapper.updateByPrimaryKey(news);
        } else {
            return newsMapper.insert(news);
        }
    }
}
